package handler

import (
	"net/http"

	"go-file-perception-model/internal/logger"
	"go-file-perception-model/internal/model"
	"go-file-perception-model/internal/service"

	"go.uber.org/zap"

	"github.com/gin-gonic/gin"
)

// DBDirectoryTreeHandler 基于数据库的目录树处理器
type DBDirectoryTreeHandler struct {
	dbDirectoryTreeService *service.DBDirectoryTreeService
}

// NewDBDirectoryTreeHandler 创建基于数据库的目录树处理器实例
func NewDBDirectoryTreeHandler(dbDirectoryTreeService *service.DBDirectoryTreeService) *DBDirectoryTreeHandler {
	return &DBDirectoryTreeHandler{
		dbDirectoryTreeService: dbDirectoryTreeService,
	}
}

// SearchFilesInDatabase 处理数据库文件搜索请求
func (h *DBDirectoryTreeHandler) SearchFilesInDatabase(c *gin.Context) {
	var req model.DBDirectoryTreeSearchRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "Invalid request format",
			"error":   err.Error(),
		})
		return
	}

	// 调用服务层进行数据库搜索
	response, err := h.dbDirectoryTreeService.SearchFilesInDatabase(req)
	if err != nil {
		logger.Error("Failed to search files in database", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to search files in database",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "Database file search completed successfully",
		"data":    response,
	})
}

// SearchFilesInDatabaseByGet 处理GET方式的数据库文件搜索请求
func (h *DBDirectoryTreeHandler) SearchFilesInDatabaseByGet(c *gin.Context) {
	// 获取查询参数
	pattern := c.Query("pattern")
	searchPath := c.Query("search_path")

	// 构建请求
	req := model.DBDirectoryTreeSearchRequest{
		Pattern:    pattern,
		SearchPath: searchPath,
	}

	// 调用服务层进行数据库搜索
	response, err := h.dbDirectoryTreeService.SearchFilesInDatabase(req)
	if err != nil {
		logger.Error("Failed to search files in database", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to search files in database",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "Database file search completed successfully",
		"data":    response,
	})
}
